package com.yayo.mangement.security.filter;

import com.alibaba.fastjson.JSON;
import com.yayo.mangement.info.UserInfo;
import com.yayo.mangement.security.config.WhiteListConfig;
import com.yayo.mangement.security.utils.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @JwtAuthenticationTokenFilter: JWT过滤器，将token解析，用户存入SecurityContextHolder中
 * @author: Yayo
 * @date: 2022/8/30 21:03
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        System.out.println(httpServletRequest.getRequestURL());
        //判断token是否过期并且合法
        if(!WhiteListConfig.checkWhiteList(httpServletRequest.getRequestURI()) && JwtUtil.checkToken(httpServletRequest)){
            UserInfo userInfo = JwtUtil.getAccountByJwtToken(httpServletRequest);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userInfo, null,null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //判断当次访问时，token是否不到一小时到期，如果是，则刷新token返回给前端，如果超过一小时，则返回当前token
            if(JwtUtil.checkExpInHour(httpServletRequest)){
                String token = JwtUtil.getToken(userInfo.getUserId().toString(), JSON.toJSONString(userInfo));
                httpServletResponse.setHeader("authorization", token);
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
